package gizwits.kit;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

public class HttpKit {
	
	private final static OkHttpClient client = new OkHttpClient();
	private final static Headers headers = new Headers.Builder()
			.add("Content-type", "text/html;charset=utf-8")
			.build();
	private final static Headers headers2 = new Headers.Builder()
	.add("Content-type", "application/json")
	.add("Accept", "application/json")
	.build();
	
	public static String post(String url, Map<String, Object> params){
		try{
			String result = post2(url, params);
			log(result);
			return result;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	public static String posts(String url, Map<String, Object> params){
		try{
			String result = post3(url, params);
			log(result);
			return result;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	
	public static String post2(String url, Map<String, Object> params) throws Exception{
		FormEncodingBuilder builder = new FormEncodingBuilder();
		if(params!=null){
			for(Entry<String, Object> param : params.entrySet()){
				builder.add(param.getKey(), String.valueOf(param.getValue()));
			}
		}
		
		Request request = new Request.Builder()
				.headers(headers)
				.url(url)
				.post(builder.build())
				.build();
		Response response = client.newCall(request).execute();

		if(!response.isSuccessful()){
			throw new IOException("Unexpected code " + response);
		}
		return response.body().string();
	}
	
	public static String post3(String url, Map<String, Object> params) throws Exception{
		FormEncodingBuilder builder = new FormEncodingBuilder();
		if(params!=null){
			for(Entry<String, Object> param : params.entrySet()){
				builder.add(param.getKey(), String.valueOf(param.getValue()));
			}
		}
		
		Request request = new Request.Builder()
				.headers(headers2)
				.url(url)
				.post(builder.build())
				.build();
		Response response = client.newCall(request).execute();

//		if(!response.isSuccessful()){
//			throw new IOException("Unexpected code " + response);
//		}
		return response.body().string();
	}
	
	
	public final static void log(Object obj){
		System.out.println(obj);
	}
}
